// Copyright 2007 Helsinki Institute for Information Technology
// and the authors.
//
// Authors: Harri Hämäläinen <harri.hamalainen@helsinki.fi>
//          Toni Ruottu <toni.ruottu@iki.fi>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

onload = function () {
    var q = Util.get_params();
    var collection = location.pathname.split('/')[2];
    

    if (q.page == 'search' && q.query) {
        new SearchView(collection, q.query);
    } else {
        new MainView(collection);
    }
};


function MainView (collection) {
    var MAX_TAGS = 3;
    var connector = new TrackerConnector();

    var html = '<div class="thisplace"><h1><a href="/collection/' + collection + '/web/index.html">' + HttpConnector.doGet('/collection/'+ collection+'/info/title') + '</a></h1>'

    html += '<table><tr><th>Tags</th><th>Name</th><th>Published</th><th></th><th>Size</th><th title="Seeders">S</th><th title="Leechers">L</th></tr>';

    var collections = connector.getCollections(collection);

    for (var c=0; c<collections.length; c++) {

        collection2 = collections[c];

        collection2name = HttpConnector.doGet('/collection/'+ collection2+'/info/title?timeout=0')

        var torrents = connector.getTorrentfiles(collection2);

        var infos = connector.getTorrentinfos(collection2);


        for (var i = 0; i<torrents.length; i++) {
            var infohash = torrents[i][0].match(/(\w*)\/file\/.*$/)[1];
            var torrent = torrents[i][0].match(/\w*\/file\/(.*)$/)[1];
            var friendlyname = name;

            var torrentinfo = null;

            for (var j=0; j<infos.length; j++) {
                if (infos[j][0] == infohash+"/info/"+torrent+"/info") {
                    torrentinfo = infos[j][1].evalJSON(true);
                }
            }

            var status = HttpConnector.doGet("/island/"+collection2+"/status?info_hash="+infohash).evalJSON(true);

            html += "<tr><td class=\"tags\">"+TrackerUtils.getNiceTags(connector.getTags(infohash, torrent, collection2), MAX_TAGS, null)+"</td><td class=\"filename\"><a href=\"/collection/"+collection2+"/web/index.html?page=torrent_info&torrent="+infohash+"/"+torrent+"\">"+
                    TrackerUtils.friendlyName(torrent)+"</a><br /><div class=\"origin\">from <a href=\"/collection/"+ collection2 + "/web/index.html\">" + collection2name + "</a></div></td>"+
                    "<td>"+Util.getUTCFriendlyDate(torrentinfo["published"]).split(' ')[0]+"</td>"+
                    "<td class=\"get\"><a href=\"/collection/"+collection2+"/island/"+torrents[i][0]+"\"><img src=\"/static/icons/torrent_download.png\" alt=\"get torrent\" /></a></td>"+
                    "<td>"+TrackerUtils.bytesToMbytes(parseInt(torrentinfo["size"]))+"</td>"+
                    "<td>"+status["files"][infohash]["complete"]+"</td>"+
                    "<td>"+status["files"][infohash]["incomplete"]+"</td></tr>";
        }
    }
    html += '</table>';

    html += '<p class="feedlink"><a href="/coast/' + collection + '/feed"><img src="/static/icons/feed-icon-14x14.png" alt=""/> get publications as a feed</a></p></div>'
    html += '<ul class="mainmenu">';
    /*
    html += '<li><a href="">Found a new coast</a></li>'
    */
    html += '<li><a href="javascript:create_new_island(\''+collection+'\')">Found a new island</a></li>'
    html += '</ul>';
    $('view').innerHTML +=  html;
}

function SearchView(collection, tag) {
    var self = this;
    var MAX_TAGS = 3;
    var connector = new TrackerConnector();

    var html = '<div class="thisplace"><h1><a href="/collection/' + collection + '/web/index.html">' + HttpConnector.doGet('/collection/'+ collection+'/info/title') + '</a></h1>'

    html += '<h2 class="tagtitle"><span>' + tag + '</span></h2>'
    html += '<table><tr><th>Tags</th><th>Name</th><th>Published</th><th></th><th>Size</th><th title="Seeders">S</th><th title="Leechers">L</th></tr>';

    var collections = connector.getCollections(collection);

    var result = new Array();
    for (var c=0; c<collections.length; c++) {
        collection2 = collections[c];
		var subresult = TrackerUtils.searchTag(collection2, tag);
        for (var i=0; i<subresult.length; i++) {
            result.push(subresult[i]);
        }
    }

    for (var i=0; i<result.length; i++) {

        var collection2 = result[i][0].split('/')[0];
        collection2name = HttpConnector.doGet('/collection/'+ collection2+'/info/title?timeout=0')
        var infohash = result[i][0].split('/')[1];
        var torrent = result[i][0].split('/')[3];
        var torrentinfo = HttpConnector.doGet("/collection/"+collection2+"/island/"+infohash+"/info/"+torrent+"/info").evalJSON(true);

        var status = HttpConnector.doGet("/island/"+collection2+"/status?info_hash="+infohash).evalJSON(true);

        html += "<tr><td class=\"tags\">"+TrackerUtils.getNiceTags(connector.getTags(infohash, torrent, collection2), MAX_TAGS, tag )+"</td>"+
                "<td class=\"filename\"><a href=\"/collection/"+collection2+"/web/index.html?page=torrent_info&torrent="+infohash+"/"+torrent+"\">"+
                TrackerUtils.friendlyName(torrent)+"</a><br /><div class=\"origin\">from <a href=\"/collection/"+ collection2 + "/web/index.html\">" + collection2name + "</a></div></td>"+
                "<td>"+Util.getUTCFriendlyDate(torrentinfo["published"]).split(' ')[0]+"</td>"+
                "<td class=\"get\"><a href=\"/collection/"+collection2+"/island/"+result[i][0]+"\"><img src=\"/static/icons/torrent_download.png\" alt=\"get torrent\" /></a></td>"+
                "<td>"+TrackerUtils.bytesToMbytes(parseInt(torrentinfo["size"]))+"</td>"+
                "<td>"+status["files"][infohash]["complete"]+"</td>"+
                "<td>"+status["files"][infohash]["incomplete"]+"</td></tr>";
    }

    html += '</table>';

    html += '<p class="feedlink"><a href="/coast/' + collection + '/feed"><img src="/static/icons/feed-icon-14x14.png" alt=""/> get publications as feed</a></p></div>'
    html += '<ul class="mainmenu">';
    /*
    html += '<li><a href="">Found a new coast</a></li>'
    */
    html += '<li><a href="javascript:create_new_island(\''+collection+'\')">Found a new island</a></li>'
    html += '</ul>';
    $('view').innerHTML +=  html;

}
